package middle;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class Solution_438 {

    public List<Integer> findAnagrams(String s, String p) {
        List<Integer> list = new ArrayList<>();
        Map<Character, Integer> targetMap = new HashMap<>();
        char[] chars = p.toCharArray();
        for (char c : chars) {
            targetMap.put(c, targetMap.getOrDefault(c, 0) + 1);
        }

        char[] array = s.toCharArray();
        Map<Character, Integer> map = new HashMap<>();
        int un_same = p.length();
        int left = 0, right = -1;
        int left_limit = s.length() - p.length();
        for (; left <= left_limit; ) {
            int num = right - left + 1;
            if (num >= p.length()) {
                if (un_same == 0) {
                    list.add(left);
                }
                char c = array[left];
                Integer oldCount = map.getOrDefault(c, 0);
                int count = un_same - Math.abs(targetMap.getOrDefault(c, 0) - oldCount);
                un_same = count + Math.abs(targetMap.getOrDefault(c, 0) - oldCount + 1);
                map.put(c, oldCount - 1);
                left++;
            } else {
                right++;
                char c = array[right];
                Integer oldCount = map.getOrDefault(c, 0);
                int count = un_same - Math.abs(targetMap.getOrDefault(c, 0) - oldCount);
                un_same = count + Math.abs(targetMap.getOrDefault(c, 0) - oldCount - 1);
                map.put(c, oldCount + 1);
            }
        }
        return list;
    }

    public static void main(String[] args) {
        Solution_438 model = new Solution_438();
        System.out.println(model.findAnagrams("cbaebabacd", "abc"));
        System.out.println(model.findAnagrams("abab", "ab"));
    }
}
